package handler

import (
	"context"
	"go_final/mxshop_srvs/userop_srv/global"
	"go_final/mxshop_srvs/userop_srv/model"
	messagepb "go_final/mxshop_srvs/userop_srv/proto/protofile/message"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type MessageServer struct{}

func (s MessageServer) MessageList(c context.Context, request *messagepb.MessageRequest) (*messagepb.MessageListResponse, error) {
	var messages []model.LeavingMessage
	res := global.DB.Where(model.LeavingMessage{
		UserID: request.UserId,
	}).Find(&messages)

	if res.Error != nil {
		return nil, res.Error
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.Internal, "没有留言记录")
	}

	rsp := messagepb.MessageListResponse{
		Total: int32(res.RowsAffected),
	}

	for _, message := range messages {
		rsp.Data = append(rsp.Data, &messagepb.MessageResponse{
			Id:          message.ID,
			UserId:      message.UserID,
			MessageType: message.MessageType,
			Subject:     message.Subject,
			Message:     message.Message,
			File:        message.File,
		})
	}

	return &rsp, nil
}

func (s MessageServer) CreateMessage(c context.Context, request *messagepb.MessageRequest) (*messagepb.MessageResponse, error) {
	// TODO 为了严谨性, 需要先调用用户服务查询userID是否存在
	message := model.LeavingMessage{
		UserID:      request.UserId,
		MessageType: request.MessageType,
		Subject:     request.Subject,
		Message:     request.Message,
	}
	if request.File != "" {
		message.File = request.File
	}

	res := global.DB.Save(&message)
	if res.Error != nil {
		return nil, res.Error
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.Internal, "新建留言失败")
	}

	return &messagepb.MessageResponse{
		Id: message.ID,
	}, nil
}
